package com.pulanit.pangu.admin.web.controller.business;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pulanit.pangu.admin.business.api.entity.*;
import com.pulanit.pangu.admin.business.api.param.FieldPageIn;
import com.pulanit.pangu.admin.business.api.service.*;
import cn.hutool.core.lang.Assert;
import com.gitee.pulanos.pangu.framework.sdk.dto.Result;
import com.gitee.pulanos.pangu.framework.sdk.dto.page.PageResult;
import com.pulanit.pangu.admin.common.AppContext;
import com.pulanit.pangu.admin.system.api.entity.RoleEntity;
import com.pulanit.pangu.admin.system.api.entity.UserEntity;
import com.pulanit.pangu.admin.system.api.param.PageIn;
import com.pulanit.pangu.admin.system.api.param.UserPageIn;
import com.pulanit.pangu.admin.system.api.service.RoleService;
import com.pulanit.pangu.admin.system.api.service.UserService;
import com.pulanit.pangu.admin.system.dao.mapper.RoleMapper;
import com.pulanit.pangu.admin.system.dao.mapper.UserMapper;
import com.pulanit.pangu.admin.system.manager.UserManager;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import com.gitee.pulanos.pangu.framework.sdk.dto.page.PagingUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 领域表 前端控制器
 * </p>
 *
 * @author 天鸣
 * @since 2024-03-04
 */
@RestController
@RequestMapping("/api/business/field")
public class FieldController {

    @Autowired
    private IFieldService fieldService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserManager userManager;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IArticleEditService articleEditService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IFieldExpertService fieldExpertService;

    @Autowired
    private IArticleExpertService articleExpertService;


    /**
     * 分页
     */
    @GetMapping("/page")
    public Result<PageResult<Field>> list(FieldPageIn fieldPageIn) {
        Page page = PagingUtil.createPage(fieldPageIn);
        LambdaQueryWrapper<Field> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotEmpty(fieldPageIn.getKeyword()), Field::getFieldName, fieldPageIn.getKeyword()).orderByAsc(Field::getSort).orderByDesc(Field::getCreateTime);
        Page<Field> resultPage = fieldService.page(page, wrapper);
        return Result.success(PagingUtil.transformPageResult(resultPage));
    }

    /**
     * 获取列表-字典
     *
     * @return
     */
    @GetMapping("/dicList")
    public Result<List<HashMap>> dicList() {
        LambdaQueryWrapper<Field> wrapper= new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Field::getSort);
        List<Field> list = fieldService.list(wrapper);
        List<HashMap> hashMaps = new ArrayList<>();
        list.forEach(item->{
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("label",item.getFieldName());
            hashMap.put("value",item.getId());
            hashMaps.add(hashMap);
        });
        return Result.success(hashMaps);
    }

    /**
     * 获取领域列表专家
     *
     * @return
     */
    @GetMapping("/fieldExpert")
    public Result<List<UserEntity>> fieldExpert(@RequestParam("fieldId") Long id) {
        Assert.notNull(id, "ID 不能为空");
        //搜索该领域下用户
        LambdaQueryWrapper<FieldExpert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FieldExpert::getFieldId, id);
        List<FieldExpert> list = fieldExpertService.list(lambdaQueryWrapper);
        List<Long> userIds = list.stream().map(FieldExpert::getExpertUserId).collect(Collectors.toList());
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(UserEntity.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("password"));
        List<UserEntity> userEntities = ListUtil.list(false);
        if (userIds.size() > 0) {
            userEntities = userMapper.selectBatchIds(userIds);
        }
        return Result.success(userEntities);
    }

    /**
     * 获取非领域列表专家
     *
     * @return
     */
    @GetMapping("/unFieldExpert")
    public Result<PageResult<UserEntity>> unFieldExpert(PageIn pageIn) {
        Page<UserEntity> page = PagingUtil.createPage(pageIn);
        //搜索角色id通过专家标志
        LambdaQueryWrapper<RoleEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleEntity::getRoleKey, "expert").last("limit 1");
        List<RoleEntity> roleEntities = roleMapper.selectList(wrapper);
        //获取专家用户
        List<UserEntity> userEntities = userManager.listUsersByRoleId(roleEntities.get(0).getId());

        //搜索该领域下用户
        LambdaQueryWrapper<FieldExpert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FieldExpert::getFieldId, pageIn.getFieldId());
        List<FieldExpert> list = fieldExpertService.list(lambdaQueryWrapper);
        List<Long> userIds = list.stream().map(FieldExpert::getExpertUserId).collect(Collectors.toList());

        //去掉领域下已经存在的用户
        List<UserEntity> collect = userEntities.stream().filter(item -> !ArrayUtil.contains(userIds.toArray(), item.getId())).collect(Collectors.toList());

        //手动分页
        List<UserEntity> resultCollect = new ArrayList<>();
        int totalSize;
        int totalPage;
        totalSize = collect.size();
        totalPage = PageUtil.totalPage(totalSize, Convert.toInt(page.getSize()));
        if (page.getCurrent() - 1 <= totalPage) {
            resultCollect = CollUtil.page(Convert.toInt(page.getCurrent() - 1), Convert.toInt(page.getSize()), collect);

        }
        return Result.success(PagingUtil.transformPageResult(page, resultCollect));
    }

    /**
     * 获取该领域列表专家-未分配
     *
     * @return
     */
    @GetMapping("/unCurrentFieldExpert")
    public Result<PageResult<UserEntity>> unCurrentFieldExpert(PageIn pageIn) {
        Assert.notNull(pageIn.getFieldId(), "ID 不能为空");
        Assert.notNull(pageIn.getArticleId(), "文稿ID 不能为空");
        Page<UserEntity> page = PagingUtil.createPage(pageIn);
        //搜索该领域下用户
        LambdaQueryWrapper<FieldExpert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FieldExpert::getFieldId, pageIn.getFieldId());
        List<FieldExpert> list = fieldExpertService.list(lambdaQueryWrapper);
        List<Long> userIds = list.stream().map(FieldExpert::getExpertUserId).collect(Collectors.toList());
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(UserEntity.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("password"));
        List<UserEntity> userEntities = ListUtil.list(false);
        if (userIds.size() > 0) {
            userEntities = userMapper.selectBatchIds(userIds);
        }
        //排除已经分配的专家
        LambdaQueryWrapper<ArticleExpert> expertLambdaQueryWrapper = new LambdaQueryWrapper<>();
        expertLambdaQueryWrapper.eq(ArticleExpert::getArticleId, pageIn.getArticleId());
        List<ArticleExpert> list1 = articleExpertService.list(expertLambdaQueryWrapper);
        List<Long> collect = list1.stream().map(item -> item.getExpertUserId()).collect(Collectors.toList());

        List<UserEntity> collect1 = userEntities.stream().filter(item -> !ArrayUtil.contains(collect.toArray(), item.getId())).collect(Collectors.toList());

        //添加专家待审核数量
        for (int i = 0; i < collect1.size(); i++) {
            LambdaQueryWrapper<ArticleExpert> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ArticleExpert::getCheckStatus, 0)
                    .eq(ArticleExpert::getRefuse, 1)
                    .eq(ArticleExpert::getExpertUserId, collect1.get(i).getId());
            long count = articleExpertService.count(wrapper);
            collect1.get(i).setCheckNum(Convert.toInt(count));
        }

        //手动分页
        List<UserEntity> resultCollect = new ArrayList<>();
        int totalSize;
        int totalPage;
        totalSize = collect.size();
        totalPage = PageUtil.totalPage(totalSize, Convert.toInt(page.getSize()));
        if (page.getCurrent() - 1 <= totalPage) {
            resultCollect = CollUtil.page(Convert.toInt(page.getCurrent() - 1), Convert.toInt(page.getSize()), collect1);

        }
        return Result.success(PagingUtil.transformPageResult(page, resultCollect));
    }

    /**
     * 获取该领域列表专家-已分配
     *
     * @return
     */
    @GetMapping("/currentFieldExpert")
    public Result<List<UserEntity>> currentFieldExpert(@RequestParam("articleId") Long articleId) {
        Assert.notNull(articleId, "ID 不能为空");
        LambdaQueryWrapper<ArticleExpert> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleExpert::getArticleId, articleId);
        List<ArticleExpert> list = articleExpertService.list(wrapper);
        List<Long> userIds = list.stream().map(ArticleExpert::getExpertUserId).collect(Collectors.toList());
        LambdaQueryWrapper<UserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(UserEntity.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("password"));
        List<UserEntity> userEntities = ListUtil.list(false);
        if (userIds.size() > 0) {
            userEntities = userMapper.selectBatchIds(userIds);
        }
        return Result.success(userEntities);
    }

    /**
     * 文稿分配领域专家
     *
     * @return
     */
    @PostMapping("/allotArticleExpert")
    public Result<Void> allotArticleExpert(@RequestParam("articleId") Long articleId, @RequestParam("ids") List<Long> ids) {
        Assert.notNull(articleId, "文章 ID 不能为空");
        Assert.notEmpty(ids, "人员 ID 不能为空");
        for (int i = 0; i < ids.size(); i++) {
            ArticleExpert articleExpert = new ArticleExpert();
            articleExpert.setArticleId(articleId);
            articleExpert.setExpertUserId(ids.get(i));
            articleExpert.setCheckStatus(0);
            articleExpert.setRefuse(0);
            articleExpert.setCreateDate(DateTime.now().toLocalDateTime());
            articleExpert.setEditUserId(AppContext.getUserInfo().getId());
            articleExpertService.save(articleExpert);
        }
        //编辑关联文稿
        ArticleEdit articleEdit = new ArticleEdit();
        articleEdit.setArticleId(articleId);
        articleEdit.setEditUserId(AppContext.getUserInfo().getId());
        articleEditService.save(articleEdit);
        Article article = new Article();
        article.setId(articleId);
        article.setAllot(1);
        articleService.updateById(article);
        return Result.success();
    }

    /**
     * 文稿重新分配领域专家
     *
     * @return
     */
    @PostMapping("/anewAllotArticleExpert")
    public Result<Void> anewAllotArticleExpert(@RequestParam("articleId") Long articleId,
                                               @RequestParam("ids") List<Long> ids,
                                               @RequestParam("expertUserId") Long expertUserId) {
        Assert.notNull(articleId, "文章 ID 不能为空");
        Assert.notEmpty(ids, "人员 ID 不能为空");
        Assert.notNull(expertUserId, "替换专家 ID 不能为空");
        LambdaQueryWrapper<ArticleExpert> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleExpert::getArticleId,articleId)
                .eq(ArticleExpert::getExpertUserId,expertUserId);
        boolean remove = articleExpertService.remove(wrapper);
        if (!remove){
            return Result.fail("重新分配失败");
        }
        for (int i = 0; i < ids.size(); i++) {
            ArticleExpert articleExpert = new ArticleExpert();
            articleExpert.setArticleId(articleId);
            articleExpert.setExpertUserId(ids.get(i));
            articleExpert.setCheckStatus(0);
            articleExpert.setRefuse(0);
            articleExpert.setCreateDate(DateTime.now().toLocalDateTime());
            articleExpert.setEditUserId(AppContext.getUserInfo().getId());
            articleExpertService.save(articleExpert);
        }
        return Result.success();
    }


    /**
     * 关联领域专家
     *
     * @return
     */
    @PostMapping("/grantFieldExpert")
    public Result<Void> grantFieldExpert(@RequestParam("fieldId") Long fieldId, @RequestParam("ids") List<Long> ids) {
        Assert.notNull(fieldId, "领域 ID 不能为空");
        Assert.notEmpty(ids, "人员 ID 不能为空");
        for (int i = 0; i < ids.size(); i++) {
            FieldExpert fieldExpert = new FieldExpert();
            fieldExpert.setFieldId(fieldId);
            fieldExpert.setExpertUserId(ids.get(i));
            fieldExpertService.save(fieldExpert);
        }
        return Result.success();
    }

    /**
     * 取消关联领域专家
     *
     * @return
     */
    @PostMapping("/cancelFieldExpert")
    public Result<Void> cancelFieldExpert(@RequestParam("fieldId") Long fieldId, @RequestParam List<Long> ids) {
        Assert.notNull(fieldId, "领域 ID 不能为空");
        Assert.notEmpty(ids, "人员 ID 不能为空");
        for (int i = 0; i < ids.size(); i++) {
            LambdaQueryWrapper<FieldExpert> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FieldExpert::getFieldId, fieldId);
            wrapper.eq(FieldExpert::getExpertUserId, ids.get(i));
            fieldExpertService.remove(wrapper);
        }
        return Result.success();
    }

    /**
     * 获取详情
     *
     * @return
     */
    @GetMapping("/detail")
    public Result<Field> detail(@RequestParam("id") Long id) {
        Assert.notNull(id, "ID 不能为空");
        Field field = fieldService.getById(id);
        return Result.success(field);
    }

    /**
     * 保存
     *
     * @param field
     * @return
     */
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Field field) {
        field.setCreateTime(DateTime.now().toLocalDateTime());
        fieldService.save(field);
        return Result.success();
    }

    /**
     * 修改
     *
     * @param field
     * @return
     */
    @PostMapping("/update")
    public Result<Void> update(@RequestBody Field field) {
        fieldService.updateById(field);
        return Result.success();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result<Void> delete(@RequestParam("id") Long id) {
        Assert.notNull(id, "ID 不能为空");
        LambdaQueryWrapper<FieldExpert> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FieldExpert::getFieldId, id);
        long count = fieldExpertService.count(wrapper);
        if (count > 0) {
            return Result.fail("有专家在该领域下，不可以删除");
        }

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getFieldId, id);
        long count1 = articleService.count(queryWrapper);
        if (count1 > 0) {
            return Result.fail("有文稿在该领域下，不可以删除");
        }

        fieldService.removeById(id);
        return Result.success();
    }

    /**
     * 批量删除
     */
    @PostMapping("/batchDelete")
    public Result<Void> batchDelete(@RequestParam List<Long> ids) {
        Assert.notEmpty(ids, "ID 不能为空");
        fieldService.removeBatchByIds(ids);
        return Result.success();
    }

}
